package cn.datawin.common.state.action;

import cn.datawin.common.state.StateMachineUtil;
import cn.datawin.common.state.entity.BaseBasket;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.squirrelframework.foundation.fsm.UntypedAnonymousAction;
import org.squirrelframework.foundation.fsm.UntypedStateMachine;

import java.util.List;

import static cn.datawin.common.state.constant.State.END;


/**
 * 状态扫尾处理action
 * Created by hyygavin on 2019/3/28.
 */
public class StateWindUpAction extends UntypedAnonymousAction {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void execute(Object ruleFrom, Object ruleTo, Object event, Object context, UntypedStateMachine stateMachine) {
        BaseBasket basket  = (BaseBasket) context;
        logger.debug("StateWindUpAction---ruleFrom---{}---ruleTo---{}",ruleFrom,ruleTo);
        String action = ruleTo.toString();

        //检测是否是内部状态跳转,直接开启内部transition的流程
        if(StrUtil.isNotBlank(basket.getLocalInEvent())){
            stateMachine.fire(basket.getLocalInEvent(),basket);
            return;
        }

        //检测中间状态的手动将basket缓存的end标志位改为true，直接跳转到end状态
        logger.debug("StateWindUpAction---basket.isEnd---{}",basket.isEnd());
        if(basket.isEnd()) {
            stateMachine.fire(StateMachineUtil.event(action, END), basket);
            return;
        }

        //普通的情况
        List<String> lines = basket.getLines();
        int index = lines.indexOf(action);
        logger.debug("StateWindUpAction---lines---{}---index---{}",lines,index);
        //到达最后处理action 跳转到end状态
        if(index==lines.size()-1){
            stateMachine.fire(StateMachineUtil.event(action,END),basket);
        }else{//还未到最后，跳转到basket::lines中的下一个状态
            String next = lines.get(index + 1);
            stateMachine.fire(StateMachineUtil.event(action,next),basket);
        }

    }
}
